package main

import "strconv"

func calculateSimple(s []byte) int {
	result := 0
	current := 0
	sign := 1
	for i := 0; i < len(s); i++ {
		c := s[i]
		 if c >= '0' && c <= '9' {
			current = current*10 + int(c-'0')
		} else {
			result += sign * current
			current = 0
			if c == '+' {
				sign = 1
			} else if c == '-' {
				if s[i+1] == '-' {
					sign = 1
					i++
				} else {
					sign = -1
				}
			}
		}
	}
	result += sign * current
	return result
}

func int2bytes(v int) []byte {
	return []byte(strconv.Itoa(v))
}

func calculate(s string) int {
	var tokens []byte
	var bracket []int // 左括号在 tokens 中的位置，当栈用
	for i := range s {
		c := s[i]
		if c == ' ' {
			continue
		} else if c == '(' {
			tokens = append(tokens, c)
			bracket = append(bracket, len(tokens)-1)
		} else if c == ')' {
			start := bracket[len(bracket)-1]
			bracket = bracket[:len(bracket)-1]
			sub := tokens[start+1:]
			subResult := calculateSimple(sub)
			tokens = tokens[:start] // 弹出左括号及之后的部分
			tokens = append(tokens, int2bytes(subResult)...)
		} else {
			tokens = append(tokens, c)
		}
	}
	return calculateSimple(tokens)
}

func main() {
	println(calculate("- (3 - (- (4 + 5) ) )"))
}